package cn.lblbc.ziptool

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cn.lblbc.ziptool.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var selectedArchiveUri: Uri? = null
    
    private val openArchiveContract = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
        uri?.let {
            try {
                // 获取持久化权限
                val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                contentResolver.takePersistableUriPermission(it, takeFlags)
                
                selectedArchiveUri = it
                
                // 直接跳转到新Activity展示压缩包内容
                val intent = Intent(this, ArchiveContentActivity::class.java).apply {
                    putExtra("archive_uri", it.toString())
                    putExtra("archive_name", getFileName(it))
                }
                startActivity(intent)
            } catch (e: Exception) {
                Log.e("MainActivity", "Error processing selected file", e)
                Toast.makeText(this, "处理文件时出错: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        if (permissions.all { it.value }) {
            openArchiveFile()
        } else {
            Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        setupListeners()
        // 处理从外部分享进来的文件
        handleIncomingIntent(intent)
    }
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_settings -> {
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 处理已经运行时从外部分享进来的文件
        intent?.let { handleIncomingIntent(it) }
    }
    
    /**
     * 处理从外部应用分享进来的文件
     */
    private fun handleIncomingIntent(intent: Intent) {
        val action = intent.action
        val type = intent.type
        
        Log.d("MainActivity", "Handling incoming intent: action=$action, type=$type")
        
        if ((Intent.ACTION_SEND == action || Intent.ACTION_SEND_MULTIPLE == action || Intent.ACTION_VIEW == action) && type != null) {
            when {
                type.startsWith("application/") -> {
                    if (Intent.ACTION_SEND == action) {
                        // 单个文件分享
                        val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
                        uri?.let {
                            Log.d("MainActivity", "Processing single shared file: $it")
                            processSharedFile(it)
                        }
                    } else if (Intent.ACTION_SEND_MULTIPLE == action) {
                        // 多个文件分享
                        val uris = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
                        uris?.firstOrNull()?.let { 
                            Log.d("MainActivity", "Processing first of multiple shared files: $it")
                            processSharedFile(it)
                        }
                    } else if (Intent.ACTION_VIEW == action) {
                        // 直接查看文件
                        val uri = intent.data
                        uri?.let {
                            Log.d("MainActivity", "Processing viewed file: $it")
                            processSharedFile(it)
                        }
                    }
                }
            }
        } else if (Intent.ACTION_VIEW == action) {
            // 处理没有指定type的VIEW操作
            val uri = intent.data
            uri?.let {
                Log.d("MainActivity", "Processing viewed file without type: $it")
                processSharedFile(it)
            }
        }
    }
    
    private fun processSharedFile(uri: Uri) {
        try {
            // 尝试获取持久化权限，但不强制要求
            try {
                val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                contentResolver.takePersistableUriPermission(uri, takeFlags)
            } catch (e: SecurityException) {
                Log.w("MainActivity", "Could not take persistable URI permission: ${e.message}")
                // 如果无法获取持久化权限，继续处理文件
            }
            
            selectedArchiveUri = uri
            
            // 直接跳转到新Activity展示压缩包内容
            val archiveIntent = Intent(this, ArchiveContentActivity::class.java).apply {
                putExtra("archive_uri", uri.toString())
                putExtra("archive_name", getFileName(uri))
            }
            startActivity(archiveIntent)
        } catch (e: Exception) {
            Log.e("MainActivity", "Error processing shared file", e)
            Toast.makeText(this, "处理分享文件时出错: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun setupListeners() {
        binding.selectZipButton.setOnClickListener {
            checkPermissionsAndOpenFile()
        }
        
        binding.settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }
    
    private fun checkPermissionsAndOpenFile() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                openArchiveFile()
            } else {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
        } else {
            val permissions = arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            
            if (permissions.all {
                    ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
                }) {
                openArchiveFile()
            } else {
                requestPermissionLauncher.launch(permissions)
            }
        }
    }
    
    private fun openArchiveFile() {
        openArchiveContract.launch(arrayOf(
            "application/zip",
            "application/x-rar-compressed",
            "application/x-7z-compressed",
            "application/gzip",
            "application/x-tar",
            "application/x-compressed-tar",
            "application/vnd.android.package-archive", // APK files
            "*/*"
        ))
    }
    
    private fun getFileName(uri: Uri): String {
        var result: String? = null
        contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex("_display_name")
                if (nameIndex >= 0) {
                    result = cursor.getString(nameIndex)
                }
            }
        }
        return result ?: "unknown"
    }
}